package itsm.isperp.module.controller.performance;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.performance.PerPerformance;
import itsm.isperp.module.entity.performance.PerPerformanceItem;
import itsm.isperp.module.entity.performance.PerPerformanceItemDetail;
import itsm.isperp.module.service.performance.PerPerformanceItemDetailService;
import itsm.isperp.module.service.performance.PerPerformanceItemService;
import itsm.isperp.module.service.performance.PerPerformanceService;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 控制器
 * 
 * @author lizx
 * @date 2017-08-29 10:18
 */
@Controller
@RequestMapping("performance/performanceItemDetail")
public class PerPerformanceItemDetailController extends
    BaseController<PerPerformanceItemDetail> {

  @Autowired
  protected PerPerformanceItemDetailService perPerformanceItemDetailService;

  @Override
  public PerPerformanceItemDetailService getService() {
    return this.perPerformanceItemDetailService;
  }

  @Override
  public String getPageTitle() {
    return "绩效考核";
  }

  @RequestMapping("listData")
  @ResponseBody
  public List<Map<String, Object>> listData(JqGridRequest request,
      HttpServletRequest req) {
    String sourceId = req.getParameter("sourceId");
    request
        .addFilterRule("per_user_submit_id", JqGridFilterRuleOp.eq, sourceId);
    return this.getService().findAllDetailByRequest(request);
  }

  @RequestMapping("updateValue")
  @ResponseBody
  public ResultMessage updateValue(HttpServletRequest req) {
    try {
      String id = req.getParameter("id");
      String situation = req.getParameter("situation");
      String perUserSubmitId = req.getParameter("perUserSubmitId");
      String selfScore = req.getParameter("selfScore");
      PerPerformanceItemDetail tmodeal = this.getService().findOne(id);
      PerPerformanceItemDetail model = null;
      if (tmodeal == null) {
        model = new PerPerformanceItemDetail();
        model.setId(HibernateUUIDGenerator.generate());
      } else {
        model = tmodeal;
      }
      model.setPerUserSubmitId(perUserSubmitId);
      model.setSelfScore(Float.parseFloat(selfScore));
      model.setSituation(situation);
      this.getService().saveOrUpdate(model);
      return ResultMessage.success();
    } catch (Exception ex) {
      return ResultMessage.failure(ex.getMessage());
    }
  }

  @RequestMapping("updateValue2")
  @ResponseBody
  public ResultMessage updateValue2(HttpServletRequest req) {
    try {
      String id = req.getParameter("id");
      String managerEvaluate = req.getParameter("managerEvaluate");
      String perUserSubmitId = req.getParameter("perUserSubmitId");
      String managerScore = req.getParameter("managerScore");

      PerPerformanceItemDetail tmodeal = this.getService().findOne(id);
      PerPerformanceItemDetail model = null;
      if (tmodeal == null) {
        model = new PerPerformanceItemDetail();
        model.setId(HibernateUUIDGenerator.generate());
      } else {
        model = tmodeal;
      }
      model.setPerUserSubmitId(perUserSubmitId);
      model.setManagerEvaluate(managerEvaluate);
      model.setManagerScore(Float.parseFloat(managerScore));
      this.getService().saveOrUpdate(model);
      return ResultMessage.success();
    } catch (Exception ex) {
      return ResultMessage.failure(ex.getMessage());
    }
  }

  @RequestMapping("edit")
  @Override
  public ModelAndView edit(String id, HttpServletRequest req) throws Exception {
    ModelAndView mv = this.getModelAndView();
    PerPerformanceItemDetail model = null;
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    String type = req.getParameter("type");
    String curUserName = ContextHolder.getLoginUsername();
    PerPerformanceItemDetail tmodeal = this.getService().findOne(id);

    if (tmodeal == null) {
      model = new PerPerformanceItemDetail();
      model.setId(HibernateUUIDGenerator.generate());
    } else {
      model = tmodeal;
    }

    {
      String cpType = model.getComputeType();
      if (cpType.equals("系统")) {
        String cpSql = model.getComputeSql();
        String startDate = "";
        String endDate = "";
        Float sysScore = null;
        cpSql = cpSql.replace("{username}", curUserName)
            .replace("{startDate}", startDate).replace("{endDate}", endDate);
        Float result = jdbcTemplate.queryForObject(cpSql, Float.class);
        Float cpTarget = Float.parseFloat(model.getComputeTarget()) / 100;
        Float tr = result / cpTarget;
        if (tr > 1) {
          sysScore = (float) (100 * model.getWeight());
        } else {
          DecimalFormat decimalFormat = new DecimalFormat(".0");
          String ts = decimalFormat.format(model.getWeight() * tr);
          sysScore = Float.parseFloat(ts);
        }
        model.setSelfScore(sysScore);
        mv.addObject("cpSysScore", sysScore);

      }
      //model.setPerItemId(perItemId);
    }
    mv.addObject("type", type);
    mv.addObject("model", model);
    return mv;
  }
  

  @RequestMapping("insertPerSettingItem")
  @ResponseBody
  public ResultMessage insertPerSettingItem(HttpServletRequest req) {
    try {
      String perSettingId = req.getParameter("perSettingId");
      String perUserSubmitId = req.getParameter("perUserSubmitId");
      String sql = "delete from per_performance_item_detail where per_user_submit_id='"
          + perUserSubmitId + "'";
      JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
      jdbcTemplate.execute(sql);
      String sql2 = "INSERT INTO per_performance_item_detail(id,per_user_submit_id,NAME,target,referenc_point,weight,compute_type,compute_sql,compute_target)"
          + " SELECT UUID(),'"
          + perUserSubmitId
          + "',NAME,target,referenc_point,weight,compute_type,compute_sql,compute_target"
          + " FROM per_performance_item WHERE per_setting_id='"
          + perSettingId
          + "'";
      jdbcTemplate.execute(sql2);
      return ResultMessage.success();
    } catch (Exception ex) {
      return ResultMessage.failure(ex.getMessage());
    }
  }

}
